"""
文档处理API接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.models.base import get_db
from app.services.enhanced_document_processor import EnhancedDocumentProcessor

router = APIRouter(prefix="/api/documents", tags=["documents"])

# 请求模型
class ProcessDocumentRequest(BaseModel):
    file_path: str

class ProcessDirectoryRequest(BaseModel):
    directory_path: Optional[str] = None

# 初始化服务（使用增强版）
document_processor = EnhancedDocumentProcessor()


@router.post("/process")
async def process_document(
    request: ProcessDocumentRequest,
    db: Session = Depends(get_db)
):
    """处理单个文档文件"""
    try:
        result = document_processor.process_document(db, request.file_path)
        
        return {
            "success": True,
            "message": "文档处理成功",
            "result": result
        }
        
    except FileNotFoundError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文档处理失败: {str(e)}"
        )


@router.post("/process-directory")
async def process_directory(
    request: ProcessDirectoryRequest,
    db: Session = Depends(get_db)
):
    """处理知识库目录中的所有文档"""
    try:
        result = document_processor.process_knowledge_base_directory(
            db, 
            request.directory_path
        )
        
        return {
            "success": True,
            "message": "目录处理完成",
            "result": result
        }
        
    except FileNotFoundError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"目录处理失败: {str(e)}"
        )


@router.post("/upload")
async def upload_document(
    file: UploadFile = File(...),
    db: Session = Depends(get_db)
):
    """上传并处理文档文件"""
    try:
        # 检查文件类型
        allowed_extensions = ['.pdf', '.txt', '.md', '.docx']
        file_extension = None
        
        for ext in allowed_extensions:
            if file.filename.lower().endswith(ext):
                file_extension = ext
                break
        
        if not file_extension:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"不支持的文件类型。支持的格式: {', '.join(allowed_extensions)}"
            )
        
        # 保存上传的文件
        from app.core.config import settings
        from pathlib import Path
        import uuid
        
        upload_dir = Path(settings.knowledge_base_path) / "uploads"
        upload_dir.mkdir(exist_ok=True)
        
        # 生成唯一文件名
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = upload_dir / unique_filename
        
        # 保存文件
        with open(file_path, "wb") as buffer:
            content = await file.read()
            buffer.write(content)
        
        # 处理文档
        result = document_processor.process_document(db, str(file_path))
        
        return {
            "success": True,
            "message": "文件上传并处理成功",
            "original_filename": file.filename,
            "saved_path": str(file_path),
            "result": result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"文件上传处理失败: {str(e)}"
        )


@router.get("/parse-pdf/{file_name}")
async def parse_pdf_file(file_name: str):
    """解析特定的PDF文件"""
    try:
        from app.core.config import settings
        from pathlib import Path
        
        # 构建文件路径
        file_path = Path(settings.knowledge_base_path) / file_name
        
        if not file_path.exists():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"文件不存在: {file_name}"
            )
        
        if not file_path.suffix.lower() == '.pdf':
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="只支持PDF文件"
            )
        
        # 解析PDF
        parsed_data = document_processor.pdf_parser.parse_pdf(str(file_path))
        
        # 移除base64图片数据以减小响应大小
        for image in parsed_data.get("images", []):
            if "base64_data" in image:
                image["has_image_data"] = True
                del image["base64_data"]
        
        return {
            "success": True,
            "message": "PDF解析成功",
            "data": parsed_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"PDF解析失败: {str(e)}"
        )


@router.get("/list-files")
async def list_knowledge_base_files():
    """列出知识库中的所有文件"""
    try:
        from app.core.config import settings
        from pathlib import Path
        
        knowledge_base_path = Path(settings.knowledge_base_path)
        
        if not knowledge_base_path.exists():
            return {
                "success": True,
                "files": [],
                "message": "知识库目录不存在"
            }
        
        files = []
        supported_extensions = ['.pdf', '.txt', '.md', '.docx']
        
        for file_path in knowledge_base_path.rglob("*"):
            if file_path.is_file() and file_path.suffix.lower() in supported_extensions:
                relative_path = file_path.relative_to(knowledge_base_path)
                
                files.append({
                    "name": file_path.name,
                    "path": str(relative_path),
                    "full_path": str(file_path),
                    "extension": file_path.suffix.lower(),
                    "size_bytes": file_path.stat().st_size,
                    "modified_time": file_path.stat().st_mtime
                })
        
        return {
            "success": True,
            "files": files,
            "total_count": len(files)
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取文件列表失败: {str(e)}"
        )


@router.get("/stats")
async def get_processing_stats(db: Session = Depends(get_db)):
    """获取文档处理统计信息"""
    try:
        from app.models.operation import OperationDocument, OperationCategory
        
        # 统计操作文档数量
        total_documents = db.query(OperationDocument).count()
        
        # 按分类统计
        categories = db.query(OperationCategory).all()
        category_stats = []
        
        for category in categories:
            doc_count = db.query(OperationDocument).filter(
                OperationDocument.category_id == category.id
            ).count()
            
            category_stats.append({
                "category_name": category.name,
                "document_count": doc_count
            })
        
        # 获取知识库统计
        knowledge_stats = document_processor.knowledge_service.get_collection_stats()
        
        return {
            "success": True,
            "stats": {
                "total_documents": total_documents,
                "categories": category_stats,
                "knowledge_base": knowledge_stats
            }
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取统计信息失败: {str(e)}"
        )
